import streamlit as st
import pandas as pd
from audit import get_calc_audit_logs
import datetime
import io
import csv
from data_utils import load_calculator_by_id

def calc_audit_logs_page():
    """计算日志页面"""
    st.title("计算日志")

    # 显示所有计算器的审计日志
    st.subheader("计算器审计日志")

    # 获取所有计算器的审计日志
    audit_logs = get_calc_audit_logs()

    if not audit_logs:
        st.info("暂无操作记录")
        return

    # 时间范围筛选
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input(
            "开始日期",
            value=None,
            key="sys_audit_start_date"
        )
    with col2:
        end_date = st.date_input(
            "结束日期",
            value=None,
            key="sys_audit_end_date"
        )

    # 获取所有操作用户列表
    all_users = list(set(log['username'] for log in audit_logs))
    # 用户筛选
    user_filter = st.selectbox(
        "按用户筛选",
        ["(全部)"] + all_users,
        key="sys_audit_user_filter"
    )

    # 获取所有计算器ID列表
    all_calc_ids = list(set(str(log['calc_id']) for log in audit_logs))
    # 计算器ID筛选
    calc_id_filter = st.selectbox(
        "按计算器ID筛选",
        ["(全部)"] + sorted(all_calc_ids),
        key="sys_audit_calc_id_filter"
    )

    # 操作类型筛选
    all_actions = list(set(log['action'] for log in audit_logs))
    action_filter = st.selectbox(
        "按操作类型筛选",
        ["(全部)"] + all_actions,
        key="sys_audit_action_filter"
    )

    # 应用筛选条件
    filtered_logs = audit_logs

    if start_date:
        filtered_logs = [
            log for log in filtered_logs
            if datetime.datetime.strptime(log["date"], "%Y-%m-%d").date() >= start_date
        ]
    if end_date:
        filtered_logs = [
            log for log in filtered_logs
            if datetime.datetime.strptime(log["date"], "%Y-%m-%d").date() <= end_date
        ]
    if user_filter != "(全部)":
        filtered_logs = [
            log for log in filtered_logs
            if log["username"] == user_filter
        ]
    if calc_id_filter != "(全部)":
        filtered_logs = [
            log for log in filtered_logs
            if str(log["calc_id"]) == calc_id_filter
        ]
    if action_filter != "(全部)":
        filtered_logs = [
            log for log in filtered_logs
            if log["action"] == action_filter
        ]

    # 显示筛选结果统计
    st.write(f"共找到 {len(filtered_logs)} 条记录")

    # 修改数据表格显示基本信息，添加计算器名称并增强已删除计算器的显示
    log_table = []
    deleted_calc_names = {}  # 缓存已删除计算器的名称

    for log in filtered_logs:
        # 使用数据库加载计算器
        calc = load_calculator_by_id(log['calc_id'])
        if calc:
            calc_name = calc.name
        else:
            calc_name = "未知计算器 (已删除)"

        log_table.append({
            "时间": f"{log['date']} {log['time']}",
            "计算器": calc_name,
            "计算器ID": log['calc_id'],
            "操作者": log['username'],
            "操作类型": log['action'],
            "详情": log['details']
        })

    st.dataframe(
        pd.DataFrame(log_table),
        use_container_width=True
    )

    # 使用选择框显示详细信息
    if any(log.get('old_value') or log.get('new_value') for log in filtered_logs):
        st.write("#### 修改详情")
        selected_log = st.selectbox(
            "选择记录查看详细修改内容",
            options=[
                f"{log['date']} {log['time']} | C-{log['calc_id']} | {log['username']} | {log['action']}"
                for log in filtered_logs
            ],
            key="sys_audit_detail_selector"
        )

        if selected_log:
            idx = [
                f"{log['date']} {log['time']} | C-{log['calc_id']} | {log['username']} | {log['action']}"
                for log in filtered_logs
            ].index(selected_log)
            log = filtered_logs[idx]

            if log.get('action') == 'update_status':
                st.write(f"**修改前状态：** {log.get('old_value', '')}")
                st.write(f"**修改后状态：** {log.get('new_value', '')}")
            elif log.get('action') == 'delete_calc':
                st.write("**删除的计算器信息：**")
                st.json(log.get('old_value', ''))
            else:
                if log.get('old_value') and log.get('new_value'):
                    col1, col2 = st.columns(2)
                    with col1:
                        st.write("**修改前**")
                        if "name" in log['old_value']:
                            st.write(f"名称: {log['old_value']['name']}")
                        if "code" in log['old_value']:
                            st.write("代码:")
                            st.code(log['old_value']['code'], language='python')
                        if "inputs" in log['old_value']:
                            st.write("输入参数:")
                            st.dataframe(pd.DataFrame(log['old_value']['inputs']))
                    with col2:
                        st.write("**修改后**")
                        if "name" in log['new_value']:
                            st.write(f"名称: {log['new_value']['name']}")
                        if "code" in log['new_value']:
                            st.write("代码:")
                            st.code(log['new_value']['code'], language='python')
                        if "inputs" in log['new_value']:
                            st.write("输入参数:")
                            st.dataframe(pd.DataFrame(log['new_value']['inputs']))

    # 导出功能
    if st.button("导出操作记录"):
        csv_buffer = io.StringIO()
        fieldnames = ["timestamp", "calc_id", "username", "action", "details"]
        writer = csv.DictWriter(csv_buffer, fieldnames=fieldnames)
        writer.writeheader()
        for log in filtered_logs:
            writer.writerow({
                "timestamp": f"{log['date']} {log['time']}",
                "calc_id": log['calc_id'],
                "username": log['username'],
                "action": log['action'],
                "details": log['details']
            })
        csv_data = csv_buffer.getvalue().encode("utf-8")
        st.download_button(
            label="下载CSV文件",
            data=csv_data,
            file_name="calculator_audit_logs.csv",
            mime="text/csv"
        )
